package com.gip.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.gip.mapper.DataMapper;
import com.gip.mapper.OrderMapper;
import com.gip.pojo.*;
import com.gip.service.CustomerService;
import com.gip.service.OrderService;
import com.gip.service.UserService;
import com.gip.utils.R;
import com.gip.vo.OrderVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class DataController {

    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;
    @Autowired
    CustomerService customerService;
    @Autowired
    DataMapper dataMapper;
    @Autowired
    OrderMapper orderMapper;

    /**
     * 用户数据控制
     */
    @RequestMapping("/findUser")
    public String findUser(int page, int limit, String searchParams) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("index", (page - 1) * limit);
        map.put("limit", limit);
//        System.out.println("输出");
//        System.out.println(searchParams);
        if (searchParams != null) {
            JSONObject jsonObject = JSON.parseObject(searchParams);
            String userName = jsonObject.getString("userName");
            System.out.println(userName);
            String phone = jsonObject.getString("phone");
            String email = jsonObject.getString("email");
            String password = jsonObject.getString("password");
            map.put("userName", userName);
            map.put("phone", phone);
            map.put("email", email);
            map.put("password", password);
        }

        List<User> list = userService.findUserByIf(map);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code", 0);
        int i = userService.conutUser();
        hashMap.put("count", i);
        hashMap.put("data", list);
        R r = new R();
        r.setCode(0);
        r.setCount(i);
        r.setData(list);
        return JSONObject.toJSONString(r);
    }

    @GetMapping("/testPage")
    //测试分页插件pageHelper功能
    public PageInfo testPage() {
        //开始的页数和数目
        //PageHelper.startPage(page,rowNum);
        //开始处和数目
        //PageHelper.offsetPage(start,rowNum);
        PageHelper.startPage(1, 10);
        List<User> list = userService.findAllUser();
        PageInfo page = new PageInfo(list);
        return page;
    }

    @PostMapping("/updateUser")
    public Map hello(String data) {
        System.out.println(data);
        JSONObject jsonObject = JSON.parseObject(data);
        int id = jsonObject.getInteger("id");
        String userName = jsonObject.getString("userName");
        String phone = jsonObject.getString("phone");
        String email = jsonObject.getString("email");
        Integer role = jsonObject.getInteger("role");
        Integer state = jsonObject.getInteger("state");
        User user = new User();
        user.setId(id);
        user.setUserName(userName);
        user.setPhone(phone);
        user.setEmail(email);
        user.setRole(role);
        user.setState(state);
        // 调用更新
        userService.upDateUser(user);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("status", "success");
        hashMap.put("msg", "success");
        return hashMap;
    }

    @PostMapping("/addUser")
    public Map addUser(String data) {
        JSONObject jsonObject = JSON.parseObject(data);
        String userName = jsonObject.getString("userName");
        String password = jsonObject.getString("password");
        String phone = jsonObject.getString("phone");
        String email = jsonObject.getString("email");
        Integer role = jsonObject.getInteger("role");

        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setPhone(phone);
        user.setEmail(email);
        user.setRole(role);
        int i = userService.addUser(user);
        HashMap<String, Object> hashMap = new HashMap<>();
        if (i >= 1) {
            hashMap.put("status", "success");
            hashMap.put("msg", "success");
        } else {
            hashMap.put("status", "error");
        }
        return hashMap;
    }

    @PostMapping("/delete")
    public Map delete(int id) {
        System.out.println(id);
        // 调用删除
        userService.deleteUser(id);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("status", "success");
        hashMap.put("msg", "success");
        return hashMap;
    }

    @PostMapping("/deleteUsers")
    public String deleteUsers(String data) {
        ArrayList<Integer> list = new ArrayList<>();
        JSONArray objects = JSON.parseArray(data);
        for (int i = 0; i < objects.size(); i++) {
            JSONObject jsonObject = objects.getJSONObject(i);
            Integer id = jsonObject.getInteger("id");
            System.out.println("id:" + id);
            list.add(id);
        }

        // 调用删除
        int i = userService.deleteUsers(list);
        R r = new R();
        if (i >= 1) {
            r.setCode(1);
            r.setStatus("success");
            r.setMsg("操作成功");
        } else {
            r.setStatus("error");
            r.setMsg("操作失败");
        }

        return JSONObject.toJSONString(r);
    }

    /**
     * 订单数据控制
     */
//    @RequestMapping("findOrders")
//    public Map findOrders(int page, int limit, String searchParams) {
//
//        HashMap<String, Object> map = new HashMap<>();
//        if (searchParams != null) {
//            JSONObject jsonObject = JSON.parseObject(searchParams);
//            String id = jsonObject.getString("id");
//            String customerId = jsonObject.getString("customerId");
//            String userId = jsonObject.getString("userId");
//            String payType = jsonObject.getString("payType");
//            map.put("id", id);
//            map.put("customerId", customerId);
//            map.put("userId", userId);
//            map.put("payType", payType);
//        }
//        PageHelper.startPage(page, limit);
//        List<Order> list = orderService.findAllOrders(map);
//        int count = orderService.countOrders();
//        HashMap<String, Object> Hashmap = new HashMap<>();
//        Hashmap.put("code", 0);
//        Hashmap.put("msg", "success");
//        Hashmap.put("count", count);
//        Hashmap.put("data", list);
//        return Hashmap;
//    }
    @RequestMapping("findOrders")
    public String findOrders(@RequestBody OrderVo orderVo) {

        PageHelper.startPage(orderVo.getPage(), orderVo.getLimit());
        System.out.println(orderVo);
        List<Order> allNewOrders = orderService.findAllNewOrders(orderVo.getOrder());
        int countOrders = orderService.countOrders();
        R r = new R();
        if (allNewOrders != null) {
            r.setCode(0);
            r.setStatus("success");
            r.setMsg("成功获取数据");
            r.setData(allNewOrders);
            r.setCount(countOrders);
        } else {
            r.setCode(400);
            r.setStatus("error");
            r.setMsg("获取失败");
            r.setCount(0);
        }

        return JSONObject.toJSONString(r);
    }

    @PostMapping("/updateOrder")
    public String updateOrder(Order order) {
        System.out.println(order);
        int i = orderService.updateOrder(order);
        R r = new R();
        r.setCode(0);
        if (i >= 1) {
            r.setStatus("success");
            r.setMsg("修改成功");
        } else {
            r.setStatus("error");
            r.setMsg("修改失败");
        }
        return JSONObject.toJSONString(r);

    }

    //    @PostMapping("/deleteOrder")
//    public Map deleteOrder(int id) {
//        System.out.println(id);
//        // 调用删除
//        int i = orderService.deleteOrder(id);
//        HashMap<String, Object> hashMap = new HashMap<>();
//        if (i >= 1) {
//            hashMap.put("status", "success");
//            hashMap.put("msg", "success");
//        } else {
//            hashMap.put("status", "error");
//        }
//        return hashMap;
//    }
    @PostMapping("/deleteOrder")
    public String deleteOrder(int id) {
        // 调用删除
        int i = orderService.deleteOrder(id);
        R r = new R();
        r.setCode(0);
        if (i >= 1) {
            r.setStatus("success");
            r.setMsg("成功");
        } else {
            r.setStatus("error");
            r.setMsg("失败");
        }
        return JSONObject.toJSONString(r);
    }

    @PostMapping("/deleteOrders")
    public String deleteOrders(String data) {
        ArrayList<Integer> list = new ArrayList<>();
        JSONArray objects = JSON.parseArray(data);
        for (int i = 0; i < objects.size(); i++) {
            JSONObject jsonObject = objects.getJSONObject(i);
            Integer id = jsonObject.getInteger("id");
//            System.out.println("id:" + id);
            list.add(id);
        }

        // 调用删除
        int i = orderService.deleteOrders(list);
        R r = new R();
        if (i >= 1) {
            r.setStatus("success");
            r.setMsg("删除成功");
        } else {
            r.setStatus("error");
            r.setMsg("删除失败");
        }

        return JSONObject.toJSONString(r);
    }

    @PostMapping("/addOrder")
    public String addOrder(Order order) {
//        老版本是解析发来的json字符串
//        System.out.println(data);
//        JSONObject jsonObject = JSON.parseObject(data);
//        Integer customerId = jsonObject.getInteger("CustomerId");
//        Date payDate = jsonObject.getDate("payDate");
//        Date maturityDate = jsonObject.getDate("maturityDate");
//        Double cost = jsonObject.getDouble("cost");
//        Integer userId = jsonObject.getInteger("userId");
//        String processingType = jsonObject.getString("processingType");

//        永远不要相信前台，判断空值后台一定要做，前台只是装B下
//        Order order = new Order();
//        if (customerId != null) {
//            order.setCustomerId(customerId);
//        }
//        if (payDate != null) {
//            order.setPayDate(payDate);
//        }
//        if (maturityDate != null) {
//            order.setMaturityDate(maturityDate);
//        }
//        if (cost != null) {
//            order.setCost(cost);
//        }
//        if (userId != null) {
//            order.setUserId(userId);
//        }
//        if (processingType != null) {
//            order.setProcessingType(processingType);
//        }
//
//
//        int i = orderService.addOrder(order);
//        HashMap<String, Object> hashMap = new HashMap<>();
//        if (i >= 1) {
//            hashMap.put("status", "success");
//            hashMap.put("msg", "success");
//        } else {
//            hashMap.put("status", "error");
//        }
//        return hashMap;

        System.out.println(order);
        R r = new R();
        r.setCode(0);
        //先检查有没有这个客户先
        Customer customerById = customerService.findCustomerById(order.getCustomerId());
        if (customerById == null) {
            r.setStatus("error");
            r.setMsg("系统不存在此客户，请先补充客户信息!");
            return JSONObject.toJSONString(r);
        }
        //取出之前记录
        Record record = orderMapper.findRecord(order.getCustomerId());

        //取出前台选择的paytime
        Integer payTime = order.getPayTime();
        double orderCost;
        Date maturityDate;
        List<Cost> cost = dataMapper.findCost();
        HashMap<String, String> map = new HashMap<>();
        for (Cost cost1 : cost) {
            map.put(cost1.getTypeName(), cost1.getValue());
        }
        if (order.getProcessingType().equals("包月")) {
            Double monthCost = Double.valueOf(map.get("包月"));
            orderCost = payTime * monthCost;
            order.setCost(orderCost);

            //日历对象
            Calendar cal = Calendar.getInstance();
            cal.setTime(order.getPayDate());

            // 获取年
            int year = cal.get(Calendar.YEAR);
            // 获取月
            int month = cal.get(Calendar.MONTH);
            // 获取日
            int date = cal.get(Calendar.DATE);

            int newMonth = month + payTime;
            if (newMonth > 12) {
                newMonth = newMonth - 12;
                year = year + 1;
            }
            //到期时间日历对象
            Calendar maturity = Calendar.getInstance();
            maturity.set(year, newMonth, date);
            maturityDate = maturity.getTime();
            //放进roder对象里面
            order.setMaturityDate(maturityDate);


            if(record!=null){
                if(record.getMaturityDate().compareTo(order.getPayDate())<0){
                    //在他之前
                    Calendar cal1 = Calendar.getInstance();
                    cal1.setTime(order.getPayDate());
                    // 获取年
                    int year1 = cal1.get(Calendar.YEAR);
                    // 获取月
                    int month1 = cal1.get(Calendar.MONTH) ;
                    // 获取日
                    int date1 = cal1.get(Calendar.DATE);

                    month1 = month1 + payTime;

                    if (month1 > 12) {
                        month1 = month1 - 12;
                        year1 = year1 + 1;
                    }

                    cal1.set(year1, month1, date1);
                    Date newDate = cal1.getTime();
                    record.setMaturityDate(newDate);
                    record.setTypeName("包月客户");
                    orderMapper.updateTime(record);

                }else{

                    //在他之后
                    Calendar cal1 = Calendar.getInstance();
                    cal1.setTime(record.getMaturityDate());
                    // 获取年
                    int year1 = cal1.get(Calendar.YEAR);
                    // 获取月
                    int month1 = cal1.get(Calendar.MONTH) ;
                    // 获取日
                    int date1 = cal1.get(Calendar.DATE);

                    month1 = month1 + payTime;

                    if (month1 > 12) {
                        month1 = month1 - 12;
                        year1 = year1 + 1;
                    }

                    cal1.set(year1, month1, date1);
                    Date newDate = cal1.getTime();
                    record.setMaturityDate(newDate);
                    record.setTypeName("包月客户");
                    orderMapper.updateTime(record);
                }


            }else{
                Record record1 = new Record();
                record1.setMaturityDate(order.getMaturityDate());
                record1.setCustomerId(order.getCustomerId());
                record1.setTypeName("包月客户");
                orderMapper.addTime(record1);
            }


        }
        if (order.getProcessingType().equals("包年")) {
            Double monthCost = Double.valueOf(map.get("包年"));
            orderCost = payTime * monthCost;
            order.setCost(orderCost);

            Calendar cal = Calendar.getInstance();
            cal.setTime(order.getPayDate());

            // 获取年
            int year = cal.get(Calendar.YEAR);
            // 获取月
            int month = cal.get(Calendar.MONTH);
            // 获取日
            int date = cal.get(Calendar.DATE);

            year = year + payTime;


            //到期时间日历对象
            Calendar maturity = Calendar.getInstance();
            maturity.set(year, month, date);
            maturityDate = maturity.getTime();
            //放进roder对象里面
            order.setMaturityDate(maturityDate);



            if(record!=null) {

                if (record.getMaturityDate().compareTo(order.getPayDate()) < 0) {
                    //在他之前
                    Calendar cal1 = Calendar.getInstance();
                    cal1.setTime(order.getPayDate());
                    // 获取年
                    int year1 = cal1.get(Calendar.YEAR);
                    // 获取月
                    int month1 = cal1.get(Calendar.MONTH);
                    // 获取日
                    int date1 = cal1.get(Calendar.DATE);

                    year1 = year1 + payTime;



                    cal1.set(year1, month1, date1);
                    Date newDate = cal1.getTime();
                    record.setMaturityDate(newDate);
                    record.setTypeName("包年客户");
                    orderMapper.updateTime(record);

                } else {

                    //在他之后
                    Calendar cal1 = Calendar.getInstance();
                    cal1.setTime(record.getMaturityDate());
                    // 获取年
                    int year1 = cal1.get(Calendar.YEAR);
                    // 获取月
                    int month1 = cal1.get(Calendar.MONTH);
                    // 获取日
                    int date1 = cal1.get(Calendar.DATE);

                    year1 = year1 + payTime;



                    cal1.set(year1, month1, date1);
                    Date newDate = cal1.getTime();
                    record.setMaturityDate(newDate);
                    record.setTypeName("包年客户");
                    orderMapper.updateTime(record);
                }
            }

                else{
                Record record1 = new Record();
                record1.setMaturityDate(order.getMaturityDate());
                record1.setCustomerId(order.getCustomerId());
                record1.setTypeName("包年客户");
                orderMapper.addTime(record1);
            }
        }



        int i = orderService.addOrder(order);



        if (i >= 1) {
            r.setStatus("success");
            r.setMsg("办理成功");
            r.setData(i);
        } else {
            r.setStatus("error");
            r.setMsg("办理失败");
            r.setData(i);
        }
        return JSONObject.toJSONString(r);
    }

    /**
     * 客户数据控制
     */
    @PostMapping("/findAllCustomer")
    public String findAllCustomer(int page, int limit, @RequestParam(required = false, value = "searchParams") String data) {
//        Customer customer = JSONObject.toJavaObject(jsonObject, Customer.class);
        R r = new R();


        if (data != null) {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Customer customer = jsonObject.toJavaObject(Customer.class);
            List<Customer> allCustomer = customerService.findAllCustomer(customer);
            if (allCustomer != null) {
                r.setCode(0);
                r.setData(allCustomer);
                r.setCount(allCustomer.size());
            }
        } else {
            Customer customer = new Customer();
            List<Customer> allCustomer = customerService.findAllCustomer(customer);
            r.setCode(0);
            r.setData(allCustomer);
            int count = customerService.countCustomer();
            r.setCount(count);
        }


        return JSONObject.toJSONString(r);
    }

    @PostMapping("/deleteCustomer")
    public String deleteCustomer(int id) {
        int i = customerService.deleteCustomerById(id);
        R r = new R();
        if (i >= 1) {
            r.setStatus("success");
            r.setMsg("删除成功");
        } else {
            r.setStatus("error");
            r.setMsg("删除失败");
        }
        return JSONObject.toJSONString(r);
    }

    @PostMapping("/deleteCustomers")
    public String deleteCustomers(String data) {
        ArrayList<Integer> list = new ArrayList<>();
        JSONArray objects = JSON.parseArray(data);
        for (int i = 0; i < objects.size(); i++) {
            JSONObject jsonObject = objects.getJSONObject(i);
            Integer id = jsonObject.getInteger("id");
//            System.out.println("id:" + id);
            list.add(id);
        }

        // 调用删除
        int i = customerService.deleteCustomerByIds(list);
        R r = new R();
        if (i >= 1) {
            r.setStatus("success");
            r.setMsg("删除成功");
        } else {
            r.setStatus("error");
            r.setMsg("删除失败");
        }

        return JSONObject.toJSONString(r);
    }

    @PostMapping("/updateCustomer")
    public String updateCustomer(Customer customer) {

        int i = customerService.updateCustomer(customer);
        R r = new R();
        r.setCode(0);
        if (i >= 1) {
            r.setStatus("success");
            r.setMsg("修改成功");
        } else {
            r.setStatus("error");
            r.setMsg("修改失败");
        }
        return JSONObject.toJSONString(r);

    }

    @PostMapping("/addCustomer")
    public String addOrder(Customer customer) {

//        System.out.println(customer);
        int i = customerService.addCustomer(customer);
        R r = new R();
        r.setCode(0);
        if (i >= 1) {
            r.setStatus("success");
            r.setMsg("添加成功");
            r.setData(i);
        } else {
            r.setStatus("error");
            r.setMsg("添加失败");
            r.setData(i);
        }
        return JSONObject.toJSONString(r);
    }
    //不合理，取消掉了
//    //续费请求
//    @PostMapping("rePay")
//    public String rePay(int id) {
//        R r = new R();
//        Order orderById = orderService.findOrderById(id);
//        int i = orderService.rePay(orderById);
//        if (i >= 1) {
//            r.setCode(0);
//            r.setStatus("success");
//            r.setMsg("续费成功");
//        } else {
//            r.setCode(0);
//            r.setStatus("error");
//            r.setMsg("续费失败");
//        }
//        return JSONObject.toJSONString(r);
//    }
}
